package com.process.controller;


import cn.xuyanwu.spring.file.storage.FileStorageService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.process.dao.pojoDao.FileDetailDao;
import com.process.dao.pojoDao.PracticeCourseDao;
import com.process.domain.publi.FileDetail;
import com.process.domain.publi.PracticeCourse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Description:
 * @ClassName: FileDetaiController
 * @Author: 殷凡卓
 * @Date: 2023/5/4 11:13
 */
@Slf4j
@RestController
@RequestMapping("/preview")
public class FileController {

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private FileDetailDao fileDetailDao;

    @Value("${spring.file-storage.local[0].base-path}")
    private String name;
    @Autowired
    private PracticeCourseDao practiceCourseDao;


    /**
     * 获取文件格式
     *
     * @param path
     * @return
     */
    public static String getFileExtension(Path path) {
        String fileName = path.getFileName().toString();
        int dotIndex = fileName.lastIndexOf('.');
        return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
    }

    /**
     * 下载报告
     *
     * @param stuPhone
     * @param ProcessId
     * @param servletRequest
     * @return
     * @throws IOException
     */
    @GetMapping("processTask/{stuPhone}/{ProcessId}")
    public ResponseEntity<byte[]> getProcessTask(@PathVariable String stuPhone, @PathVariable String ProcessId, ServletRequest servletRequest) throws IOException {

        FileDetail urlByProcessIdAndSubmitter = fileDetailDao.getUrlByProcessIdAndSubmitter(ProcessId, stuPhone);
        String url = urlByProcessIdAndSubmitter.getUrl();
        String filename = urlByProcessIdAndSubmitter.getFilename();
        String path = urlByProcessIdAndSubmitter.getBasePath() + filename;

        if (filename == null)
            filename = "匿名文件" + getFileExtension(Paths.get(path));

        Path path1 = Paths.get(path);
        byte[] fileContent = Files.readAllBytes(path1);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDisposition(ContentDisposition.builder("attachment").filename(filename).build());
//        return new R(Code.GET_OK, fileContent, "文件下载");
        return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
    }

    /**
     * 下载大纲
     *
     * @param courseId
     * @param servletRequest
     * @return
     */
    @GetMapping("practiceCourse/{courseId}")
    public ResponseEntity<byte[]> get(@PathVariable long courseId, ServletRequest servletRequest) throws IOException {
        //获取我的电话号码
        String username = (String) servletRequest.getAttribute("username");
        PracticeCourse practiceCourse = practiceCourseDao.selectOne(new LambdaQueryWrapper<PracticeCourse>()
                .eq(PracticeCourse::getCourseId, courseId));
        String path = practiceCourse.getPath();
        String filename = practiceCourse.getFilename();

        if (filename == null)
            filename = "匿名文件" + getFileExtension(Paths.get(path));
        Path path1 = Paths.get(path);
        byte[] fileContent = Files.readAllBytes(path1);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDisposition(ContentDisposition.builder("attachment").filename(filename).build());
        return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
    }
}
